<template>
    <div>
        <!--app为整个组件的根元素-->
      <div ref="status"></div>
      <div ref="result"></div>
      <div ref="map"></div>
      <input type="text" id="address" readonly class="address-input">
    </div>    
  </template>
  
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
/*在Vue3中使用时,需要引入Vue3中的shallowRef方法(使用shallowRef进行非深度监听,
因为在Vue3中所使用的Proxy拦截操作会改变JSAPI原生对象,所以此处需要区别Vue2使用方式对地图对象进行非深度监听,
否则会出现问题,建议JSAPI相关对象采用非响应式的普通对象来存储)*/
// import { shallowRef } from '@vue/reactivity';
// import {ref} from "vue";
//import AMap from '@amap/amap-jsapi-loader';
//项目加载时即获得用户的定位信息
export default {
  name: 'locationSearch',
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: 'a06b202f0e99d85437d0a5e778eb6bcb'
      };

      AMapLoader.load({
        key: '771416183bdd6f18d141c0d35d65014d',
        version: '2.0',
        plugins: ['AMap.CitySearch']
      }).then((AMap) => {
        AMap.plugin('AMap.Geolocation', () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            position: 'RB',
            offset: [10, 20],
            zoomToAccuracy: true
          });
          const mapContainer = this.$refs.map; // 获取地图容器的引用
          const statusContainer = this.$refs.status; // 获取状态容器的引用
          const resultContainer = this.$refs.result; // 获取结果容器的引用
          
          const map = new AMap.Map(mapContainer); // 初始化地图
          map.addControl(geolocation);
          geolocation.getCurrentPosition((status, result) => {
            if (status === 'complete') {
              this.onComplete(result, statusContainer, resultContainer); // 将状态容器和结果容器作为参数传递

              // 将经纬度转换为地址
                AMap.plugin('AMap.Geocoder', () => {
                const geocoder = new AMap.Geocoder({
                    city: "010", // 城市设为北京，默认：“全国”
                    radius: 500// 范围，默认：500
                });

                const lnglat = [result.position.lng, result.position.lat]; // 获取经纬度信息

                geocoder.getAddress(lnglat, function(status, result) {
                    console.log('将经纬度转换为地址'+status, result);
                    if (status === 'complete' && result.regeocode) {
                    const address = result.regeocode.formattedAddress;
                    document.getElementById('address').value = address; // 将地址信息显示在输入框中
                    const jsonAddress = JSON.stringify(address);
                    sessionStorage.setItem('jsonAddress', jsonAddress); // 将地址信息存储到sessionStorage的"address"键下
                    } else {
                    console.error('根据经纬度查询地址失败');
                    }
                });
                });
            } else {
              this.onError(result, statusContainer, resultContainer); // 将状态容器和结果容器作为参数传递
            }
          });
        });
      }).catch((error) => {
        this.onError(error, this.$refs.status, this.$refs.result); // 将状态容器和结果容器作为参数传递
      });
    },
    onComplete(data, statusContainer, resultContainer) {
      statusContainer.innerHTML = '定位成功';
      const str = [];
      str.push('定位结果：' + data.position);
      str.push('定位类别：' + data.location_type);
      if (data.accuracy) {
        str.push('精度：' + data.accuracy + ' 米');
      }
      str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
      resultContainer.innerHTML = str.join('<br>');
    },
    onError(data, statusContainer, resultContainer) {
      statusContainer.innerHTML = '定位失败';
      resultContainer.innerHTML =
        '失败原因排查信息:' + data.message + '</br>浏览器返回信息：' + data.originMessage;
    }
  }
};

</script>

<style scoped>
.address-input {
  width: 100%;
  height: 100px;
  /* 其他样式属性 */
}
</style>